<?php

namespace App\Repositories\Criteria;


use App\Enum\Deleted;
use Bosnadev\Repositories\Criteria\Criteria;
use Bosnadev\Repositories\Contracts\RepositoryInterface as Repository;

class Condition extends Criteria
{

    public function __construct($where = null,$or = false){
        $this->where = $where;
        $this->or = $or;
    }

    public function apply($model, Repository $repository)
    {
        $where = $this->where;
        $or = $this->or;
        if($where){
            foreach ($where as $field => $value) {
                if ($value instanceof \Closure) {
                    $model = (!$or)
                        ? $model->where($value)
                        : $model->orWhere($value);
                } elseif (is_array($value)) {
                    if (count($value) === 3) {
                        list($field, $operator, $search) = $value;
                        $model = (!$or)
                            ? $model->where($field, $operator, $search)
                            : $model->orWhere($field, $operator, $search);
                    } elseif (count($value) === 2) {
                        list($field, $search) = $value;
                        $model = (!$or)
                            ? $model->where($field, '=', $search)
                            : $model->orWhere($field, '=', $search);
                    }
                } else {
                    $model = (!$or)
                        ? $model->where($field, '=', $value)
                        : $model->orWhere($field, '=', $value);
                }
            }
        }
        return $model;
    }
}
